import axios from 'axios'
import {getToken,setToken,removeToken} from '@/utils/token'
import {msgOpen} from '@/utils/msg'
import { mainStore } from '@/stores/store'
import router from '@/router/index'


//1、配置请求地址
// let baseURL = 'http://10.103.136.56:3003/xfjc' //测试
let baseURL = import.meta.env.VITE_BASE_URL //自动匹配当前环境的值


//2、创建axios对象
const service = axios.create({
    baseURL,
    timeout:6000, 
    /*
    对于 axios 跨域请求，我们只需要设置请求头和使用 withCredentials 即可。
    withCredentials 用于跨域请求时带上 cookie，这是跨域请求时容易忽略的细节。
    */ 
    //配置请求头
    headers:{
        'Content-type':'application/x-www-form-urlencoded',
        'Content-Type': 'application/json'
    },
    withCredentials: true,
})

//3、请求拦截器
service.interceptors.request.use(config => {
    const token = getToken() //获取token
    // console.log(token)
    if(token){
        // console.log(config);        
        //设置请求头Authorization为token，开头必须为"Bearer "(持牌人)
        config.headers.Authorization = `Bearer ${token}`
        const useStore = mainStore()        
        // console.log(useStore.userSessionInfo)
        if(config.method === "get") {
            // config.params = config.params || {}; // 确保params是一个对象
            config.params = {
                sessionInfo:{
                    sessionid:useStore.userSessionInfo.SESSION_ID,
                    personid:useStore.userSessionInfo.USER_ID,
                } // 会话信息
            }
        }
        if(config.method === "post") {
            // config.data = config.data || {}; // 确保data是一个对象                
            config.data.sessionInfo = {
                sessionid:useStore.userSessionInfo.SESSION_ID,
                personid:useStore.userSessionInfo.USER_ID,
            } // 会话信息       
        } 
    }  
    return config
},error => {
    // console.log(error);    
    Promise.reject(error);
})

//4、响应拦截器
service.interceptors.response.use(response => {
    // console.log(response);   
    const {authorization} = response.headers   //获取响应头Authorization中的token字符串
    // console.log(authorization)    
    if(authorization){
        setToken(authorization)  //存入token
    }else{
        if(!response.data.msg.message) {
            msgOpen(response.data.msg)            
        }else{
            msgOpen(response.data.msg.message + "：token过期")
        }        
        //清除pinia
        const useStore = mainStore()
        const logout = () => {
            removeToken()
            useStore.clearUserInfo()
            useStore.clearMenuList()
            useStore.clearAllSubTabList()
            useStore.clearDirs()
            useStore.clearPgs()
            useStore.clearUserSessionInfo()
            useStore.toggleHomeShow('/xfjc/index/home')
            router.push("/login")
        }
        logout()
    }
    
    return response.data;
},error => {
    // console.log(error);    
    return Promise.reject(error);
})
//5、导出
export default service